package management;


import pojo.entity.Goods;
import pojo.entity.ShoppingCart;
import pojo.entity.User;
import utils.DbUtil;
import utils.TimeoutScheduler;
import utils.UserConnection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.*;

import static dao.GoodsDao.*;
import static dao.ShoppingCartDao.*;
import static dao.UserDao.*;
import static management.CommonManagement.*;
import static utils.DbUtil.touchUser;
import static vmmsClient.UserClient.sendLogToService;

public class UserManagement {
    public static String USERNAME = null;  //当前登录的用户名
    public static boolean isFindAllGoods = false;  //是否查看全部商品
    public static boolean NEED_RELOGIN = false;

    /*======================================首页=========================================*/
    //登录成功
    public static void userLoginTrue() throws SQLException {

        home();
        System.out.println("请选择操作功能：");
        System.out.println("1.查询商品 2.挑选商品 3.查看余额 4.充值余额 5.查看购物车 6.联系管理员 7.退出登录 8.退出");
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            switch (ops){
                case "1":{
                    isFindAllGoods = true;
                    findAllProduct();
                    flag = false;
                    break;
                }
                case "2":{
                    isFindAllGoods = true;
                    userOpsGoods();
                    flag = false;
                    break;
                }
                case "3":{
                    findBalance();
                    flag = false;
                    break;
                }
                case "4":{
                    recharge();
                    flag = false;
                    break;
                }
                case "5":{
                    myShoppingCart();
                    flag = false;
                    break;
                }
                case "6":{
                    concatAdmin();
                    flag = false;
                    break;
                }
                case "7":{
                    setUserOnlineStatus(USERNAME, 0);
                    sendLogToService("[下线日志] 用户:" + USERNAME + " 已下线 " + java.time.LocalDateTime.now());
                    welcomePage();
                    flag = false;
                    break;
                }
                case "8":{
                    setUserOnlineStatus(USERNAME, 0);
                   System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    private static void concatAdmin() throws SQLException {
        PrintWriter out = UserConnection.getWriter();
        BufferedReader in  = UserConnection.getReader();
        if (out == null || in == null) {
            System.out.println("尚未建立长连接，请先登录。");
            return;
        }

//        out.println("IAMUser:" + USERNAME);
        touchUser(getUserByUsername(USERNAME).getId());

        Scanner sc = new Scanner(System.in);
        /* ============================================ */

        try {
            boolean flag = true;
            String[] admins = null;
            while (flag) {
                out.println("GET_ONLINE_ADMINS");
                String resp = in.readLine();
                if (resp != null && resp.startsWith("ONLINEAdmins:")) {
                    admins = resp.split(":")[1].split(",");
                    if (admins.length > 0 && !admins[0].equals("暂无")) {
//                        System.out.println("当前在线管理员：" + Arrays.toString(admins));
                        flag = false;
                    } else {
                        System.out.println("暂无在线管理员");
                        System.out.println("请选择一下操作");
                        System.out.println("1.再等一等（其他键，每30秒刷新一次） 2.返回首页 3.退出");
                        String input = sc.nextLine();
                        switch (input) {
                            case "2": {
                                userLoginTrue();
                                flag = false;
                                break;
                            }
                            case "3": {
                                flag = false;
                                System.exit(0);
                                break;
                            }
                            default: {
                                try {
                                    System.out.println("30 秒后自动重试...");
                                    Thread.sleep(30000);
                                } catch (InterruptedException ignored) {}
                                break;
                            }
                        }
                    }
                }
            }
            System.out.println("当前在线管理员：" + Arrays.toString(admins));
            System.out.println("请选择管理员（序号）：");
            for (int i = 0; i < admins.length; i++)
                System.out.printf("%d. %s%n", i + 1, admins[i]);
            String targetAdmin = admins[Integer.parseInt(sc.nextLine()) - 1];

            UserConnection.send("ENTER:" + USERNAME + ":" + targetAdmin);
            System.out.println("SYS:已与管理员 " + targetAdmin + " 建立会话，输入-1退出");

            while (true) {
                String msg = sc.nextLine();
                if ("-1".equals(msg)) break;
                UserConnection.send("CHAT:" + USERNAME + ":" + targetAdmin + ":" + msg);
                touchUser(getUserByUsername(USERNAME).getId());
                if (NEED_RELOGIN || isUserOfflineInDB()) {
                    System.out.println("【会话已过期，请重新登录】");
                    NEED_RELOGIN = false;
                    touchUser(getUserByUsername(USERNAME).getId());
                    welcomePage(); return;
                }
            }

            /* 4. 退出会话 */
            UserConnection.send("EXIT:" + USERNAME + ":" + targetAdmin);
            System.out.println("会话已结束，回车返回主菜单...");
            sc.nextLine();
            userLoginTrue();
        } catch (Exception e) {
            System.out.println("无法连接到服务，请稍后再试。");
        }
    }
    /*======================================用户挑选商品模块=========================================*/
    //用户挑选商品
    private static void userOpsGoods() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("===============请选择商品===============");
        isFindAllGoods = false;
        findAllProduct();
        System.out.println(" ");
        boolean flag = true;
        while (flag){
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            System.out.println("请输入商品名称：");
            String name = scanner.next();
            System.out.println("请输入商品数量：");
            int count = scanner.nextInt();
            try {
                if (count<=0){
                    System.out.println("商品数量不能小于0！请重新输入");
                    userOpsGoodsOperation();
                }
                Goods goods =getGoodsByName(name);
                if (goods == null){
                    System.out.println("该商品不存在！请重新输入");
                    continue;
//                    throw new RuntimeException("该商品不存在！");
                }
                if (goods.getCount() < count){
                    System.out.println("该商品库存不足！请重新输入");
                    continue;
                }
                flag = false;
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setUserId(getUserByUsername(USERNAME).getId());
                shoppingCart.setGoodsId(goods.getId());
                shoppingCart.setGoodsName(goods.getName());
                shoppingCart.setPrice(goods.getPrice());
                shoppingCart.setQuantity(count);
                addShoppingCart(shoppingCart);
                touchUser(shoppingCart.getUserId());
                System.out.println("已添加商品："+shoppingCart.getGoodsName()+"  单价："+shoppingCart.getPrice()+"  数量："+shoppingCart.getQuantity());
                //总价
                double total = shoppingCart.getPrice() * shoppingCart.getQuantity();
                System.out.println("总价为："+total+"￥");
                System.out.println(" ");
                userOpsGoodsOperation();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //用户选择商品后操作选项
    public static void userOpsGoodsOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去结算 2.继续挑选商品 3.去购物车 4.返回首页 5.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    toPay();
                    flag = false;
                    break;
                }
                case "2":{
                    userOpsGoods();
                    flag = false;
                    break;
                }
                case "3":{
                    myShoppingCart();
                    flag = false;
                    break;
                }
                case "4":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "5":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }


    /*======================================结算模块=========================================*/
    //用户支付
    private static void toPay() throws SQLException {
        System.out.println("=======================支付页面========================");
        Scanner scanner = new Scanner(System.in);
        double totalMoney = getTotalMoney();
        try {
            User user = getUserByUsername(USERNAME);
            touchUser(user.getId());
            System.out.println("当前账户余额为："+user.getMoney()+"￥");
            System.out.println("当前商品总价为："+totalMoney+"￥");
            System.out.println("是否确认支付？");
            System.out.println("y.确认支付 n.取消支付");
            String ops = scanner.next();
            if (ops.equals("y")){
                if (user.getMoney() < totalMoney){
                    System.out.println("当前账户余额不足！请充值！");
                    noMoneyOperation();
                    return;
                }
                user.setMoney(user.getMoney() - totalMoney);
                updateUser(user);
                touchUser(user.getId());
                System.out.println("支付成功！");
                //支付成功后需要修改商品列表中的数量和清空购物车
                //对应的将商品列表中的数量减去
                List<ShoppingCart> carts = querySCGoodsByUserId(getUserByUsername(USERNAME).getId());
                touchUser(getUserByUsername(USERNAME).getId());
                for (ShoppingCart cart : carts) {
                    //根据商品id查询商品
                    Goods goods = getGoodsById(cart.getGoodsId());
                    touchUser(getUserByUsername(USERNAME).getId());
                    //修改商品数量
                    goods.setCount(goods.getCount() - cart.getQuantity());
                    //修改商品
                    updateGoods(goods);
                    touchUser(getUserByUsername(USERNAME).getId());
                }
                // 1. 构造日志字符串
                String log = String.format("[购买日志] 用户:%s 购买了 %d 种商品，共 %.2f 元 | 明细：",
                        USERNAME, carts.size(), totalMoney);
                for (ShoppingCart c : carts) {
                    log += String.format("【%s x%d 单价%.2f】", c.getGoodsName(), c.getQuantity(), c.getPrice());
                }
                sendLogToService(log);
                //清空购物车
                delAllSCGoods(getUserByUsername(USERNAME).getId());
                touchUser(getUserByUsername(USERNAME).getId());
                cancalPayOrPaySuccessOperation();
            }else {
                cancalPayOrPaySuccessOperation();
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    //取消支付后操作或支付成功后的操作
    public static void cancalPayOrPaySuccessOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.返回首页 2.去购物车 3.查看余额 4.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "2":{
                    myShoppingCart();
                    flag = false;
                    break;
                }
                case "3":{
                    findBalance();
                    flag = false;
                    break;
                }
                case "4":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    flag = false;
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    //账户余额不足操作
    public static void noMoneyOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去充值 2.去购物车 3.返回首页 4.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    recharge();
                    flag = false;
                    break;
                }
                case "2":{
                    myShoppingCart();
                    flag = false;
                    break;
                }
                case "3":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "4":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }
    /*======================================余额查询模块=========================================*/
    //查看余额
    public static void findBalance() throws SQLException {
        System.out.println("=======================余额查询页面========================");
        User user = getUserByUsername(USERNAME);
        touchUser(getUserByUsername(USERNAME).getId());
        System.out.println("当前账户余额为："+user.getMoney()+"￥");
        findAllGoodsOrMarginOPeration();
    }

    /*======================================充值模块=========================================*/
    //充值
    private static void recharge() {
        System.out.println("=======================余额充值页面========================");
        Scanner scanner = new Scanner(System.in);
        try {
            User user = getUserByUsername(USERNAME);
            touchUser(getUserByUsername(USERNAME).getId());
            System.out.println("当前账户余额为："+user.getMoney()+"￥");
            System.out.println("请输入充值金额：");
            double money = scanner.nextDouble();
            user.setMoney(user.getMoney() + money);
            updateUser(user);
            System.out.println("充值成功！");
            String log = String.format("【%s】充值%.2f成功！充值余额为：%.2f ￥",USERNAME, money, money);
            sendLogToService(log);
            System.out.println(" ");
            RechargeSuccessOperation();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //充值成功后操作
    public static void RechargeSuccessOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.返回首页 2.查看余额 3.去购物车 4.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "2":{
                    findBalance();
                    flag = false;
                    break;
                }
                case "3":{
                    myShoppingCart();
                    flag = false;
                    break;
                }
                case "4":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    /*======================================购物车模块=========================================*/
    private static void myShoppingCart() throws SQLException {
        System.out.println("=======================购物车页面========================");
        List<ShoppingCart> carts = querySCGoodsByUserId(getUserByUsername(USERNAME).getId());
        touchUser(getUserByUsername(USERNAME).getId());
        if (carts == null || carts.size()==0){
            System.out.println(" ");
            System.out.println("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓");
            System.out.println("┃                               _                               _   _       _        ┃");
            System.out.println("┃     ___   _ __ ___    _ __   | |_   _   _      __ _   ___    (_) | |_    (_)  ___  ┃");
            System.out.println("┃    / _ \\ | '_ ` _ \\  | '_ \\  | __| | | | |    / _` | / __|   | | | __|   | | / __| ┃");
            System.out.println("┃   |  __/ | | | | | | | |_) | | |_  | |_| |   | (_| | \\__ \\   | | | |_    | | \\__ \\ ┃");
            System.out.println("┃    \\___| |_| |_| |_| | .__/   \\__|  \\__, |    \\__,_| |___/   |_|  \\__|   |_| |___/ ┃");
            System.out.println("┃                      |_|            |___/                                          ┃");
            System.out.println("┃                                    购物车🛒 空空如也                                 ┃");
            System.out.println("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛");
            System.out.println(" ");
            System.out.println("快去添加心仪的商品吧~~~！");
            EmptyCartOperation();
        }else {
            System.out.println("商品列表展示");
            System.out.printf("%-10s%-10s%-10s%-10s%n", "商品编号", "商品名称", "商品价格", "商品数量");
            for (int i = 0; i < carts.size(); i++) {
                ShoppingCart shoppingCart = carts.get(i);
                // 数据行
                System.out.printf("%-13d%-11s%-13.1f%-10d%n",shoppingCart.getId(), shoppingCart.getGoodsName(), shoppingCart.getPrice(), shoppingCart.getQuantity());
                }
            System.out.println(" ");
            System.out.println("当前总价为："+getTotalMoney()+"￥");
            shoppingCartOperation();
        }
    }
    //计算购物车中商品总价
    private static double getTotalMoney() throws SQLException {
        double totalMoney = 0.0;
        List<ShoppingCart> carts = querySCGoodsByUserId(getUserByUsername(USERNAME).getId());
        touchUser(getUserByUsername(USERNAME).getId());
        for (ShoppingCart sc : carts) {
            totalMoney+=sc.getPrice()*sc.getQuantity();
        }
        return totalMoney;
    }

    //查看完购物车后操作
    public static void shoppingCartOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去结算 2.修改商品数量 3.批量删除商品 4.去挑选商品 5.返回首页 6.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    toPay();
                    flag = false;
                    break;
                }
                case "2":{
                    updateShoppingCartGoodsQuantity();
                    flag = false;
                    break;
                }
                case "3":{
                    daleteBatchShoppingCartGoods();
                    flag = false;
                    break;
                }
                case "4":{
                    userOpsGoods();
                    flag = false;
                    break;
                }
                case "5":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "6":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    //批量删除购物车商品
    private static void daleteBatchShoppingCartGoods() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要删除的商品编号（批量以“,”分隔）：");
        String[] ids = scanner.next().split(",");
        int[] intIds = Arrays.stream(ids)
                .map(String::trim)
                .mapToInt(Integer::parseInt)
                .toArray();
        try {
            delBatchSCGoodsById(intIds);
            touchUser(getUserByUsername(USERNAME).getId());
            System.out.println("删除成功！");
            myShoppingCart();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //根据购物车中商品id，修改商品数量
    private static void updateShoppingCartGoodsQuantity() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            System.out.println("请输入要修改的商品编号：");
            Integer id = scanner.nextInt();
            System.out.println("请输入要修改的商品数量：");
            Integer quantity = scanner.nextInt();
            try {
                ShoppingCart shoppingCart = getSCById(id);
                touchUser(getUserByUsername(USERNAME).getId());
                if (shoppingCart == null){
                    System.out.println("操作有误，无此商品，请重试！");
                    continue;
                }
                flag = false;
                updateSCQuantityById(shoppingCart, quantity);
                touchUser(getUserByUsername(USERNAME).getId());
                System.out.println("修改成功！");
                myShoppingCart();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //购物车为空操作
    public static void EmptyCartOperation() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去挑选商品 2.返回首页 3.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    userOpsGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "3":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }


    /*======================================查询商品模块=========================================*/
    //查询全部商品
    private static void findAllProduct() {
        try {
            List<Goods> goodsList = query();
            if (goodsList.size() <= 0){
                System.out.println("很抱歉噢~，商品已全部售完啦！");
            }else {
                int count = 0;
                for (Goods goods : goodsList) {
                    //判断所有的商品数量是否为0，如果都为0，则提示商品已售完
                    if (goods.getCount() == 0){
                        count++;
                    }
                }
                if (count == goodsList.size()){
                    System.out.println("很抱歉噢~，商品已全部售完啦！");
                }
                System.out.printf("%-10s%-10s%-10s%-10s%n", "商品编号", "商品名称", "商品价格", "商品数量");
                //否则，还存在商品未售卖，则继续显示
                for (Goods goods : goodsList) {
                    System.out.printf("%-13d%-11s%-13.1f%-10d%n", goods.getId(), goods.getName(), goods.getPrice(), goods.getCount());
                }
                if (isFindAllGoods){
                    findAllGoodsOrMarginOPeration();
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //查看全部商品或查看余额后操作
    public static void findAllGoodsOrMarginOPeration() throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去挑选商品 2.去购物车 3.返回首页 4.退出");
        boolean flag = true;
        while (flag) {
            if (NEED_RELOGIN || isUserOfflineInDB()) {
                System.out.println("【会话已过期，请重新登录】");
                NEED_RELOGIN = false;
                touchUser(getUserByUsername(USERNAME).getId());
                welcomePage();          // 退回首页
                return;
            }
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    userOpsGoods();
                    flag = false;
                    break;
                }
                case "2":{
                    myShoppingCart();
                    flag = false;
                    break;
                }
                case "3":{
                    userLoginTrue();
                    flag = false;
                    break;
                }
                case "4":{
                    setUserOnlineStatus(USERNAME, 0);
                    System.exit(0);
                    break;
                }
                default:{
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }
}
